<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="100px"
        >
          <el-form-item label="供电所名称" prop="customerName">
            <el-input
              v-model="queryParams.deptName"
              placeholder="请输入供电所名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['web:CustomerRepair:add']"
            >新增
            </el-button>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="supplyList"
          row-key="deptId"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >

          <!--      展示表格-->
          <el-table-column label="名称" prop="deptName" />
          <el-table-column label="州市局" align="center" prop="city" />
          <el-table-column label="区县" align="center" prop="area" />

          <el-table-column
            label="操作"
            align="center"
            width="160"
          >
            <template slot-scope="scope">
<!--              v-hasPermi="['facilitator:service:edit']"-->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改
              </el-button>
<!--              v-hasPermi="['facilitator:service:add']"-->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleAdd(scope.row)"
              >新增</el-button>
<!--              v-hasPermi="['facilitator:service:remove']"-->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>


    <!-- 添加或修改客户报修抢修对话框 -->
    <el-dialog title="新增供电所" :visible.sync="open" width="760px" append-to-body>
      <el-form
        ref="supplyRef"
        :model="form"
        :rules="rules"
        label-width="150px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="地区" prop="region">
              <v-distpicker  @province="onChangeProvince" @city="onChangeCity" @area="onChangeArea" :province="form.province" :city="form.city" :area="form.area"  placeholder="请选择地区"></v-distpicker>
<!--              <el-input v-model="form.nickName" placeholder="请选择地区" maxlength="30" />-->
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptList" :normalizer="normalizer" placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供电所或部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入供电所或部门名称" />
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="州市供电局名称" prop="stateName">-->
<!--              <el-input v-model="form.stateName" placeholder="请输入州市供电局名称" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="区县供电局名称" prop="districtName">-->
<!--              <el-input v-model="form.districtName" placeholder="请输入区县供电局名称" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input
                v-model="form.address"
                type="textarea"
                placeholder="请输入地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="经纬度" prop="lngAndLat">
            <el-input
              v-model="form.lngAndLat"
              placeholder="请输入经纬度"
            />
          </el-form-item>
        </el-row>
        <el-form-item label="选择位置">
          <baidu-map
            style="width:100%;height:300px;display:flex;flex-direction: column-reverse;"
            :center="center"
            :zoom="zoom"
            @click="getLocation"
            @ready="handler">
            <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
            <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
            <div style="display:flex;margin-bottom: 15px">
              <bm-auto-complete v-model="searchAddress" :sugStyle="{zIndex: 999999}">
                <el-input v-model="searchAddress" style="width:95%;margin-right:15px" placeholder="输入地址"></el-input>
              </bm-auto-complete>
              <el-button type="primary" @click="getBaiduMapPoint">搜索</el-button>
            </div>
            <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
            <bm-marker v-if="infoWindowShow" :position="{lng: longitude, lat: latitude}">
              <bm-label content="" :labelStyle="{color: 'red', fontSize : '24px'}" :offset="{width: -35, height: 30}"/>
            </bm-marker>
            <!--                <bm-info-window :position="{lng: longitude, lat: latitude}" :show="infoWindowShow" @clickclose="infoWindowClose">-->
            <!--                  <p>纬度:{{this.latitude}}</p>-->
            <!--                  <p>经度:{{this.longitude}}</p>-->
            <!--                </bm-info-window>-->
          </baidu-map>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script type="text/javascript" name="CustomerRepair">
import moment from 'moment'
import VDistpicker from 'v-distpicker'
import {
  listCustomerRepair,
  getCustomerRepair,
  delCustomerRepair,
  addCustomerRepair,
  updateCustomerRepair, getAllDepts, FrimUser, designate
} from '@/api/web/CustomerRepair'
// import useUserStore from '@/store/modules/user'
import { deptTreeSelect, getUserProfile } from '@/api/system/user'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { addDept, delDept, getDept, listDept, listDeptExcludeChild, updateDept } from '@/api/system/dept'
import Treeselect from "@riophae/vue-treeselect";
import { handleTree } from '@/utils/ruoyi'
import { bdMapToTxMap } from '@/utils'

export default {
  name: "Dispatch",
  components: {Treeselect, VDistpicker },
  dicts: ['sys_flag','sys_fp'],
  data() {
    return {
      searchAddress:'',
      infoWindowShow:false,
      longitude:'',
      latitude:'',
      center: {lng: 116.413384, lat: 39.910925}, // 定位位置116.413384, 39.910925
      zoom: 13, // 地图放大等级
      deptOptions: [], // 部门树选项
      deptName: undefined,   // 部门名称
      defaultProps: {
        children: "children",
        label: "deptName"
      },
      order: {},
      dialogVisible: false,
      btnLoading: false,
      bLoad: false,
      frims: [],
      users: [],
      sys_fp: [],
      sys_flag: [],
      supplyList: [],
      open: false,
      buttonLoading: false,
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: '',
      form: {
        province: '云南省',
        city: '',
        area: ''
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptName: undefined,
        typeId: 4
      },
      rules: {
        // region: [
        //   { required: true, message: "用户ID不能为空", trigger: "change" },
        // ],
        // deptId: [
        //   { required: true, message: "归属部门不能为空", trigger: "change" },
        // ],
        stateName: [
          { required: true, message: "州市供电局名称不能为空", trigger: "blur" },
        ],
        districtName: [
          { required: true, message: "区县供电局名称不能为空", trigger: "blur" },
        ],
        deptName: [
          { required: true, message: "供电所名称不能为空", trigger: "blur" },
        ],
        // address: [{ required: true, message: "供电所地址不能为空", trigger: "blur" }],
        // lngAndLat: [{ required: true, message: "经纬度不能为空", trigger: "blur" }],
      },
      deptList: []
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  watch: {},
  methods: {
    onChangeProvince(a){
      console.log(a)
      this.form.province = a.value
      this.txt1 = a.value + '-'
      this.searchAddress = this.form.province + (this.form.city + '') + (this.form.area || '')
      this.getBaiduMapPoint()
    },
    onChangeCity(a){
      console.log(a)
      this.form.city = a.value
      this.txt2 = a.value + '-'
      this.searchAddress = this.form.province + (this.form.city + '') + (this.form.area || '')
      this.getBaiduMapPoint()
    },
    onChangeArea(a){
      console.log(a)
      this.form.area = a.value
      this.txt3 = a.value
      this.show=false
      this.searchAddress = this.form.province + (this.form.city + '') + (this.form.area || '')
      this.getBaiduMapPoint()
    },
    handler ({ BMap, map }) {
      const myGeo = new BMap.Geocoder();
      // 选择一个经纬度作为中心点
      this.point = new BMap.Point(116.413384, 39.910925); // 116.413384, 39.910925
      map.centerAndZoom(this.point, 12);
      this.BMap=BMap
      this.map=map
      const that = this
      myGeo.getLocation(this.point,function(result){
        console.log(result)
        // that.form.address = result.address; //获取到当前定位的详细地址信息
      });
      // 纬度:39.910925,经度:116.413384
      // this.form.lngAndLat = '39.910925,116.413384'
    },
    //点击获取经纬度
    getLocation(e){
      console.log(e)
      this.longitude=e.point.lng
      this.latitude=e.point.lat
      this.infoWindowShow=true
      this.center = {lng: e.point.lng, lat: e.point.lat}
      this.form.lngAndLat = `${e.point.lng},${e.point.lat}`
      const myGeo = new BMap.Geocoder();
      this.point = new BMap.Point(e.point.lng,e.point.lat); // 116.413384, 39.910925
      const that = this
      myGeo.getLocation(this.point,function(result){
        console.log(result)
        that.form.address = result.address; //获取到当前定位的详细地址信息
        that.$set(that.form, 'address', result.address)
      });
    },
    getBaiduMapPoint() {
      console.log(this.searchAddress)
      let that=this
      that.form.address = this.searchAddress;
      let myGeo = new this.BMap.Geocoder()
      myGeo.getPoint(this.searchAddress,function(point){
        if(point){
          // that.map.centerAndZoom(point,15)
          that.latitude=point.lat
          that.longitude=point.lng
          that.infoWindowShow=true
          that.center = {lng: point.lng, lat: point.lat}
          that.form.lngAndLat = `${point.lng},${point.lat}`
        }

      })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      // deptTreeSelect().then(response => {
      //   this.deptOptions = response.data;
      // });
      listDept({ typeId: 4 }).then(response => {
        this.deptOptions = handleTree(response.data, "deptId");
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    /** 查询客户报修抢修列表 */
    getList(query) {
      // console.log(this.queryParams)
      // console.log(query)
      this.loading = true;
      listDept({ typeId: 4 }).then(response => {
        this.supplyList = handleTree(response.data, "deptId");
        // this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptName: null,
      };
      this.resetForm("supplyRef");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryRef");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      listDept(this.queryParams).then(response => {
        this.deptList = handleTree(response.data, "deptId");
        // this.loading = false;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.deptId).then(response => {
        this.form = response.data;
        if (!this.form.deptInfo) {
          this.form.deptInfo = {}
        }
        this.open = true;
        this.title = "修改部门";
        listDeptExcludeChild(row.deptId).then(response => {
          this.deptList = handleTree(response.data.filter(r => r.typeId).filter(r => r.typeId !== 3).filter(r => r.typeId !== 2), "deptId");
          if (this.deptList.length == 0) {
            const noResultsOptions = { deptId: this.form.parentId, deptName: this.form.parentName, children: [] };
            this.deptList.push(noResultsOptions);
          }
        });
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["supplyRef"].validate((valid) => {
        console.log(this.form)
        if (valid) {
          let item = this.form.lngAndLat.split(',')
          let position = bdMapToTxMap(parseFloat(item[1]), parseFloat(item[0]))
          this.buttonLoading = true;
          const obj = {
            typeId: 4,
            lon: position.lng,
            lat: position.lat,
            orderNum: 1,
            deptInfo: {}
          }
          if (this.form.deptId != undefined) {
            updateDept(Object.assign(this.form, obj)).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.buttonLoading = false
            });
          } else {
            addDept(Object.assign(this.form, obj)).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.buttonLoading = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项？').then(function() {
        return delDept(row.deptId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleDisplay(row) {
      this.dialogVisible = true
      this.order = row
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "web/CustomerRepair/export",
        {
          ...this.queryParams,
        },
        `CustomerRepair_${new Date().getTime()}.xlsx`
      );
    },

  }
}
</script>
